package teamproject.graphEditor.dialogs;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.swing.AbstractButton;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.Scrollable;
import javax.swing.SwingConstants;

public class NodeRadioButtonsScrollPane extends JPanel implements Scrollable,
		MouseMotionListener {

	private ButtonGroup group = new ButtonGroup();
	private ArrayList<JRadioButton> buttonList;
	private Object[] buttons;
	private JRadioButton selected;

	public NodeRadioButtonsScrollPane(ArrayList<JRadioButton> buttonList) {
		super();
		setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
		this.buttonList = buttonList;
		buttons = buttonList.toArray();

		for (int i = 0; i < buttons.length; i++) {
			group.add((JRadioButton) buttons[i]);
		}

		selected = (JRadioButton) buttons[0];
		selected.setSelected(true);

		for (int i = 0; i < buttons.length; i++) {
			add((JRadioButton) buttons[i]);
		}

		setAutoscrolls(true);
		addMouseMotionListener(this);
	}

	@Override
	public Dimension getPreferredScrollableViewportSize() {
		return getPreferredSize();
	}

	@Override
	public int getScrollableBlockIncrement(Rectangle visibleRect,
			int orientation, int direction) {
		if (orientation == SwingConstants.HORIZONTAL)
			return visibleRect.width - 1;
		else
			return visibleRect.height - 1;
	}

	@Override
	public boolean getScrollableTracksViewportHeight() {
		return false;
	}

	@Override
	public boolean getScrollableTracksViewportWidth() {
		return false;
	}

	@Override
	public int getScrollableUnitIncrement(Rectangle visibleRect,
			int orientation, int direction) {
		return 1;
	}

	public JRadioButton getSelected() {
		JRadioButton result = null;
		Enumeration<AbstractButton> enumeration = group.getElements();
		while (enumeration.hasMoreElements()) {
			JRadioButton button = (JRadioButton) enumeration.nextElement();
			if (button.isSelected()) {
				result = button;
			}
		}

		if (result != null)
			return result;
		else
			return null;
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);
		scrollRectToVisible(r);
	}

	@Override
	public void mouseMoved(MouseEvent e) {
	}
}
